package com.ma.cloud.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Component;

/**
 * redis客户端配置
 * @author mr
 * @since 2025-06-23
 */
@Component
public class RedisClientConfig {

    /**
     * redisTemplate 序列化使用的jdkSerializeable, 存储二进制字节码, 所以自定义序列化类
     *
     * @param factory factory
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        // 创建RedisTemplate对象
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 设置连接工厂
        template.setConnectionFactory(factory);

        // 创建Jackson2JsonRedisSerializer对象
        Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
                new Jackson2JsonRedisSerializer<>(Object.class);
        // 创建ObjectMapper对象
        ObjectMapper om = new ObjectMapper();
        // 设置所有属性可见
        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 激活默认类型
        om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
        // 设置ObjectMapper对象
        jackson2JsonRedisSerializer.setObjectMapper(om);

        // 设置key序列化器
        template.setKeySerializer(new StringRedisSerializer());
        // 设置value序列化器
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // 设置hashKey序列化器
        template.setHashKeySerializer(new StringRedisSerializer());
        // 设置hashValue序列化器
        template.setHashValueSerializer(jackson2JsonRedisSerializer);

        // 初始化属性
        template.afterPropertiesSet();
        // 返回RedisTemplate对象
        return template;
    }

}
